<?php
    header('content-type:text/html;charset="utf-8"');
    //定义统一返回格式
    $responseData = array("code" => 0,"message" => "");
    // var_dump($_POST);
    //取出传过来的数据
    $username = $_POST["username"];
    $password = $_POST["password"];

    //验证
    if(!$username){
        $responseData["code"] = 1;
        $responseData["message"] = "用户名不能为空";
        echo json_encode($responseData);
        exit;
    }else if(strlen("$username") < 6){
        $responseData["code"] = 2;
        $responseData["message"] = "用户名最短6个字符";
        echo json_encode($responseData);
        exit;
    }


    if(!$password){
        $responseData["code"] = 3;
        $responseData["message"] = "密码不能为空";
        echo json_encode($responseData);
        exit;
    }

    // 1.连接数据库
    $link = mysqli_connect("localhost","root","root");

    // 2.判断是否连接成功
    if(!$link){
        $responseData['code'] = 4;
        $responseData['message'] = "数据库连接失败";
        // 返回到前台页面
        echo json_encode($responseData);
        exit; //结束后续操作
    }

    //3.设置字符集
    mysqli_set_charset($link,"utf8");

    //4.选择数据库
    mysqli_select_db($link,"租售系统");

    //5.准备sql 验证用户名是否重名
    $sql1 = "SELECT * FROM users WHERE username='{$username}' ";

    //6.发送sql
    $res = mysqli_query($link,$sql1);

    //7.取出一行数据
    $row = mysqli_fetch_assoc($res);
    if($row){
        //用户名重名
        $responseData["code"] = 5;
        $responseData["message"] = "用户已存在";
        echo json_encode($responseData);
        exit;
    }

    // md5加密
    $str = md5(md5(md5($password)."xxx")."yyy");

    //准备sql语句将数据插入数据库
    $sql2 = "INSERT INTO users(username,password) VALUE
    ('{$username}','{$str}')";

    //再次发送sql
    $res = mysqli_query($link,$sql2);

    //返回布尔值
    if(!$res){
        //注册失败
        $responseData["code"] = 6;
        $responseData["message"] = "注册失败";
        echo json_encode($responseData);
        exit;
    }else{
        //注册成功
        $responseData["message"] = "注册成功";
        echo json_encode($responseData);
    }

    //8.关闭数据库
    mysqli_close($link);
?>